import sys
import os

# 确保可以导入本地模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

try:
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from config import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_TRACK_MODIFICATIONS, SECRET_KEY, DEBUG
    from models import db, TTSTransformation
    import argparse
except ImportError:
    sys.path.append(os.path.abspath(os.path.dirname(__file__)))
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from config import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_TRACK_MODIFICATIONS, SECRET_KEY, DEBUG
    from models import db, TTSTransformation
    import argparse

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = SQLALCHEMY_TRACK_MODIFICATIONS
app.config['SECRET_KEY'] = SECRET_KEY
app.config['DEBUG'] = DEBUG

def init_database():
    """初始化数据库"""
    with app.app_context():
        try:
            # 创建所有表
            db.create_all()
            print("数据库表创建成功！")
            
            # 插入一条测试数据（可选）
            test_record = TTSTransformation(
                text="这是一条测试文本，用于验证Kitten TTS Web服务",
                voice="expr-voice-5-m",
                speed=1.0,
                duration=0.5
            )
            db.session.add(test_record)
            db.session.commit()
            print("已插入测试数据")
            
        except Exception as e:
            print(f"数据库初始化失败: {e}")

if __name__ == '__main__':
    # 解析命令行参数
    parser = argparse.ArgumentParser(description='初始化Kitten TTS Web数据库')
    parser.add_argument('--test-data', action='store_true', help='插入测试数据')
    args = parser.parse_args()
    
    print("开始初始化数据库...")
    print(f"使用的数据库连接: {app.config['SQLALCHEMY_DATABASE_URI']}")
    
    # 初始化数据库
    init_database()